<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Operasi-operasi yang berhubungan dengan database user
 * @property Form_validation form_validation
 * @author Eko Prasetyo<nir@nirleka.web.id>
 */
class Users_model extends CI_Model {

    private $user_scheme;

    public function __construct() {
        parent::__construct();
        $this->load->helper('date_gen_helper');
        $this->load->library('form_validation');
        $this->user_scheme = array(
            'NAMA' => '',
            'PASSWORD' => '',
            'ID' => '',
            'TEMPAT_LAHIR' => '',
            'TANGGAL_LAHIR' => '',
            'NO_TELP' => '',
            'GOL' => '',
            'ALAMAT' => '',
            'EMAIL' => '',
            'PEKERJAAN' => '',
            'ASAL_INSTANSI' => '',
            'JENIS_KELAMIN' => '',
            'SUMBER_CIC' => '',
            'STATUS_AMBIL_KARTU' => '',
            'NO_CIC_CARD' => '',
            'STATUS_CIC_CARD' => '',
        );
    }

    function get_user_scheme() {
        return $this->user_scheme;
    }

    /*     * *
     * Cek apakah email ada di database atau tidak. return true jika
     */

    function is_email_new($newemail, $iduser) {
        return ($this->db
                        ->select('email')
                        ->from('user')
                        ->where("id", $iduser)
                        ->get()
                        ->num_row() === 0);
    }

    /**
     * Melakukan aksi login
     * @param Array $data ['username', 'password']
     */
    public function do_login($data) {
        $id = 0;
        $foto = '';
        $nama = '';
        $password = '';
        $role = '';
        $username = '';

        if (!empty($data['username']) && !empty($data['log_password'])) {
            $tpass = md5($data['log_password']);
            $sql = $this->db
                    ->select('ID, USERNAME,FOTO, NAMA, NAMA_ROLE')
                    ->where('USERNAME', $data['username'])
                    ->where('PASSWORD', $tpass)
                    ->from("user natural join role natural join daftar_role")
                    ->get();
            //ada user
            $result = $sql->row_array();


            if ($sql->num_rows == 1) {
                if (empty($result['FOTO'])) {
                    $foto = base_url() . 'foto/default.jpg';
                } else {
                    $foto = $result['FOTO'];
                }
                $loged_data = array(
                    'id' => $result['ID'],
                    'foto' => $foto,
                    'nama' => $result['NAMA'],
                    'password' => $data['log_password'],
                    'logged_in' => true,
                    'role' => $result['NAMA_ROLE'],
                    'username' => $result['USERNAME']
                );
                $this->session->set_userdata($loged_data);
                redirect('portal/profile_con/dashboard');
            } else {
                //tidak ada user
                $id = -1;
            }
        } else {
            //form kosong
            $id = 0;
        }
        //pesan kesalahan
        if ($id == 0)
            $this->flash_message->error('Username and password must filled');
        if ($id == -1)
            $this->flash_message->error('Username or password wrong');

        redirect('portal/profile_con');
    }

    function get_biodata($id) {
        return $result = $this->db
                ->from('user left outer join peserta using (id)')
                ->where('id', $id)
                ->get()
                ->row_array();
    }

    function get_biodata_2($id) {
        return $result = $this->db
                ->from('user')
                ->where('id', $id)
                ->get()
                ->row_array();
    }

    function is_peserta_exist($id) {
        $query = $this->db->query("select count(*) as dupe from peserta where id = '$id'");
        $row = $query->row();
        if ($row->dupe == 0)
            return false;
        else
            return true;
    }

    function update_biodata($newdata) {
        //check user sudah terdaftar atau belum di table peserta
        if (!$this->is_peserta_exist($this->session->userdata('id'))) {
            $this->db->set('id', $this->session->userdata('id'))
                    ->insert('peserta');
        }
        
        $olddata = $this->get_biodata($this->session->userdata('id'));

        $data = array_diff($newdata, $olddata);

        $this->db
                ->where('u.id', $this->session->userdata('id'))
                ->where('p.id', $this->session->userdata('id'))
                ->update('user u, peserta p', $data);

        $this->flash_message->success('Data updated');

        if (empty($data))
            $this->flash_message->info('No new data specified, data not updated');
        redirect('portal/profile_con/edit_biodata');
    }

    function update_password($newdata) {
        //check user sudah terdaftar atau belum di table peserta
        if (!$this->is_peserta_exist($this->session->userdata('id'))) {
            $this->db->set('id', $this->session->userdata('id'))
                    ->insert('peserta');
        }
        
        $sql = $this->db
                ->select('PASSWORD')
                ->where('ID', $this->session->userdata('id'))
                ->where('PASSWORD', md5($newdata['old_password']))
                ->from("user")
                ->get();
        //ada user
        $result = $sql->row_array();
        if(empty($result))
            $this->flash_message->info('Password did not match');
        else{
            if (isset($newdata['password'])) {
                $pass = $newdata['password'];
                $newdata['password'] = md5($newdata['password']);
                $this->session->set_userdata(array('password' => $pass));
            }
            $data = array(
                'PASSWORD' => md5($newdata['new_password'])
            );

            $this->db
                    ->where('u.id', $this->session->userdata('id'))
                    ->update('user u', $data);

            $this->flash_message->success('Data updated');
        }

        redirect('portal/profile_con/edit_password');
    }
    function update_foto($foto) {
        $this->db
                ->where('id', $this->session->userdata('id'))
                ->update('user', $foto);
    }

    function get_role() {
        return
                        $this->db
                        ->select('kode_pelatihan, nama_role, nama_pelatihan, angkatan')
                        ->from('mengajar_kelas mk natural join kelas natural join pelatihan natural join daftar_role')
                        ->where('mk.id', $this->session->userdata('id'))
                        ->get()
                        ->result_array();
    }

    function is_peserta() {
        return (strcmp($this->session->userdata('role'), "Peserta") == 0);
    }

    function print_data($param) {
        if (!empty($param))
            echo $param;
        else
            echo " - ";
    }

    function get_course_history(){
        $this->db->join('pelatihan','peserta_kelas.KODE_PELATIHAN=pelatihan.KODE_PELATIHAN');
        $this->db->join('term','peserta_kelas.ID_TERM=term.ID_TERM');
        return $this->db->get_where('peserta_kelas',array('ID_USER'=>$this->session->userdata('id')))->result_array();
    }
    
}

//end of file
